<template>
  <div class="page white-stage social-clients">
    <top-filter ref="topFilter" v-show="!isShowSearch" :activeItem="filterActiveItem" :filterOptions="filterOptions" @load-more="loadFilter" @change-filter="changeFilterValue" @item-selected="topFilterItemSelected" :cancelSelect="cancelSelect"></top-filter>
    <search-input v-model="searchVal" ref="searchInput" v-if="isShowSearch" @show="initSearchBodyHeight()" @search-change="searchChange" @cancel="cancelSearch" :showCancel="true" :hasFilter="false"></search-input>
    <div class="container pdt">
      <div class="soci-clients-list clearfix">
        <div v-infinite-scroll="getCustoms"
        :infinite-scroll-disabled="loading"
        infinite-scroll-distance="30"
        >
          <div class="rela-tip-main" v-if="keyword || tagName">
            <div class="rela-result-tip" @click="cancelSearch()">
              <div class="cancel-blocker" v-if="keyword">
                <span>"{{ this.keyword }}" 根据姓名显示的名单结果</span> <i class="remove-ico"><icon name="remove"></icon></i>
              </div>
              <div class="cancel-blocker" v-if="tagName">
                <span>"{{ this.tagName }}" 根据标签显示的名单结果</span> <i class="remove-ico"><icon name="remove"></icon></i>
              </div>
            </div>
          </div>
          <div class="rela-tip-main">
            <div class="rela-result-tip top-list-counter">总计{{ total }}条记录</div>
          </div>
          <div class="client-list-body">
            <custom-item
            :isChaChong="action === 'search'"
            v-for="(client, index) in clientList"
            :key="index"
            :isUsernameVisible="isUsernameVisible"
            v-model="clientList[index]"
            :showProp="false"
            propPosition="bodyTop"
            :value="refactCustom(client)" :custom_type="custom_type" :selectFollow="selectFollow"></custom-item>
          </div>
        </div>
      </div>
    </div>
    <crm-cover v-if="isShowCover" :hideCoverOnClick="true"></crm-cover>
    <crm-tabbar v-show="!isShowSearch && !isAppMode" ref="tabbar" :activeItem="custom_type=='0' ? 'h5marketing' : 'marketing'" v-if="activated"></crm-tabbar>
    <popup v-model="isShowSearch" :height="this.searchBodyHeight + 'px'" :show-mask="false" @touchstart.prevent
      style="background-color:white;" :style=" 'top:' + this.searchBodyTop + 'px;'">
      <div v-if="isShowSearch === true" class="multi-search-list">
          <div class="multi-search-group" v-if="searchVal || this.action === 'search'">
            <h3 class="multi-search-title">名单</h3>
            <div class="multi-search-item lighter" @click="search()" v-if="searchVal">
              <span class="item-icon">
                <icon name="search"></icon>
              </span>
              <div class="item-rt">
                <div class="search-item-value">搜索 "{{ searchVal }}"</div>
                <div class="search-item-link"></div>
              </div>
            </div>
          </div>
          <div class="multi-search-group"></div>
        </group>
      </div>
    </popup>
    <!-- <div class="list-counter"></div> -->
  </div>

</template>
<script>
  import { getSourceOptions } from '../lib/options/source'
  import { getChannelOptions } from '../lib/options/channel'
  import crmTabbar from '../components/crm-tabbar'
  import crmCover from '../components/crm-cover'
  import topFilter from '../components/top-filter'
  import clientItem from '../components/client-item'
  import customItem from '../components/roll-item'
  import { getCustomSource } from '../lib/client'
  import Popup from 'vux/src/components/popup'
  import Cell from 'vux/src/components/cell'
  import Group from 'vux/src/components/group'
  // only import the icons you use to reduce bundle size
  import 'vue-awesome/icons/tag'
  import 'vue-awesome/icons/search'
  import 'vue-awesome/icons/remove'
/* Register component with one of 2 methods */
  import Icon from 'vue-awesome/components/Icon'
  // import dropdownOption from '../components/dropdown-option';
  // import { SHOW_COVER } from '../store/mutation-types';
  import {loadTeamSettings, loadMemberSettings, loadFilterFunc} from '../lib/filter'
  import store from '../store'
  import SearchInput from '../components/SearchInput'
  import { mapActions, mapState } from 'vuex'
  import { mapField } from '../lib/backend'

  export default {
    props: {
      isUsernameVisible: {
        default: false
      }
    },
    data () {
      return {
        activated: true,
        loading: false,
        isMore: '',
        init: false,
        submitData: {},
        tagName: '',
        total: 0,
        action: '',
        containerHeight: 'height:' + document.body.scrollHeight + 'px;',
        page_size: 15,
        searchBodyHeight: '',
        page_index: 1,
        myTags: [],
        selectFollow: false,
        // activeItem: 'h5marketing',
        custom_type: 0,
        tagObjectCode: 'social_customer',
        isShowSearch: false,
        noDataText: '',
        originNoDataText: '暂无数据',
        filterActiveItem: {},
        searchBodyTop: 0,
        clientList: false,
        filterData: {},
        keyword: '',
        searchVal: '',
        cancelSelect: null,
        filterOptions: [
          {
            title: '搜索',
            class: 'txt-center',
            showArrow: true,
            name: 'search'
          },
          
          {
            title: '状态',
            value: '',
            class: 'txt-center',
            name: 'status',
            checked: '-1',
            options: [
              {
                text: '不限',
                value: '-1'
              },
              {
                text: '待处理',
                value: 'CRT%23'
              },
              {
                text: '导入成功',
                value: 'OK%23%23'
              },
              {
                text: '导入失败',
                value: 'FLS%23%23'
              }
            ]
          }
        ]
      }
    },

    components: {
      crmTabbar,
      crmCover,
      topFilter,
      clientItem,
      // Scroller,
      SearchInput,
      Popup,
      Cell,
      Group,
      Icon,
      customItem
    },
    activated () {
       this.activated = true
       setTimeout(() => {
         if (this.position) {
           this.$refs.my_scroller.scrollTo(this.position.left, this.position.top)
         }
       }, 100)
       this.callJsApi('biz.navigation.setTitle', {title: this.$route.query.title})
     },
     deactivated () {
       this.activated = false
       if (this.$refs.my_scroller) {
         this.position = this.$refs.my_scroller.getPosition()
         console.warn(this.position, 'this.position')
       }
     },
    methods: {

      refresh (iscroll) {
        console.log('refresh')
        this.getCustoms()
      // Refresh current data
      },
      loadFilter: loadFilterFunc,
      log () {
      },

      refactCustom (custom) {

        return custom
      },

      load (iscroll) {
        if (this.reloaded !== false) {
          this.getCustoms()
          console.log('load')
        }
        // Load new data
      },
      // 模糊查询标签
      queryTags (tag) {
        const params = Object.assign({tagObjectCode: this.tagObjectCode}, tag)
        this.findTags(params).then((response) => {
          if (response.data.errcode === 0) {
            this.myTags = response.data.myTags
          } else {
            this.myTags = []
          }
        }).catch((err) => {
          this.myTags = []
          console.log(err)
        })
      },
      // 根据标签查询名单
      queryClientByTag (tag) {
        this.keyword = ''
        this.tagName = tag.tagName
        this.isShowSearch = false
        this.clientList = []
        this.total = 0
        const params = Object.assign({tagObjectCode: this.tagObjectCode}, tag)
        this.queryObjectsByTag(params).then((response) => {
          if (response.data.errcode === 0) {
            const objectList = response.data.list
            if (objectList.length) {
              let ids = []
              objectList.forEach((elem, key) => {
                ids.push(elem.businessId)
              })
              this.queryCustomsByIds(ids).then((response) => {
                if (response.data.errcode === 0) {
                  this.clientList = Object.values(response.data.results)
                  this.total = this.clientList.length
                } else {
                  this.clientList = []
                }
                this.release()
              }).catch(() => {
                this.clientList = []
                this.release()
              })
            }
          } else {
            this.emptyCustoms()
            this.release()
          }
        }).catch(() => {
          this.emptyCustoms()
          this.release()
        })
      },
      release () {
        // if (this.$refs.my_scroller) {
        //   this.$refs.my_scroller.finishInfinite(true)
        //   this.$refs.my_scroller.finishPullToRefresh()
        // }
      },
      topFilterItemSelected (item, index) {
        console.log('topFilterItemSelected')
        if (typeof item.name !== 'undefined' && item.name === 'search') {
          this.isShowSearch = !this.isShowSearch // 搜索栏打开
          this.cancelSelect = null
        } else {
          this.isShowSearch = false // 打开的是筛选栏
        }

        if (this.isShowSearch === false && this.keyword) {
          if (this.isShowSearch === false) {
            this.keyword = ''
            this.emptyCustoms()
            this.getCustoms()
          }
        }
      },
      test () {
        console.log('test')
      },
      search () {
        this.emptyCustoms()
        this.keyword = this.searchVal
        this.getCustoms()
        this.tagName = ''
        this.isShowSearch = false
        console.log('qqqq')
        // this.sid = setTimeout(() => {
        //   if (!this.originClientList) {
        //     this.originClientList = this.clientList
        //   }
        //   this.emptyCustoms()
        //   this.keyword = value
        //   this.getCustoms()
        // }, 1000)
      },
      searchChange (value) {
        if (typeof this.sid !== 'undefined') {
          clearTimeout(this.sid)
        }
        this.sid = setTimeout(() => {
          this.queryTags({tagName: value})
        })
        this.searchVal = value
      },
      initSearchBodyHeight () {
        let height = window.innerHeight;
        let sioffsetHeight = 0;
        window['temp2'] = this.$refs.topFilter.$el
        // const tfoffsetHeight = this.$refs.topFilter.$el.offsetHeight
        if (this.$refs.searchInput) {
          sioffsetHeight = this.$refs.searchInput.$el.offsetHeight
          // const tbHeight = this.$refs.tabbar.$el.offsetHeight
          // height -= tfoffsetHeight
          height -= sioffsetHeight
        }
        // height -= tbHeight

        this.searchBodyTop = sioffsetHeight
        this.searchBodyHeight = height
      },
      getSearchBodyStyle () {
        return
      },
      // 取消搜索
      cancelSearch () {
        this.isShowSearch = false
        this.cancelSelect = true
        this.keyword = ''
        this.tagName = ''
        this.searchVal = ''
        this.emptyCustoms()
        this.getCustoms()
      },
      mergeClientList (data) {
        if (!this.clientIDs) this.clientIDs = []
        let newClients = []

        data.forEach((client, index) => {
          console.log(this.clientIDs.indexOf(client.id), 'this.clientIDs.indexOf(client.id)')

          if (this.clientIDs.indexOf(client.id) === -1) {
            newClients.push(client)
            this.clientIDs.push(client.id)
          }
        })

        if (this.loadStatus === 'refresh') {
          this.clientList = newClients.concat(this.clientList)
        } else {
          this.clientList = this.clientList.concat(newClients)
        }
      },
      getCustoms (data) {
        let defaultData = {}
        let that = this
        // console.log('***', 'getCustoms')
        // defaultData['custom_type'] = this.custom_type
        defaultData['page_size'] = this.page_size
        defaultData['page_index'] = this.page_index
        defaultData['suid'] = this.loginUser.id
        // defaultData['order_by'] = 0

        // if(this.custom_type === 1) defaultData['order_by'] = 3

        if (this.keyword) defaultData['mobile_num'] = this.keyword

        data = Object.assign(defaultData, this.filterData, data)

        console.log('getCustoms JSON.stringify(data)', JSON.stringify(data))
        this.total = 0
        let method = ''
        this.noDataText = '数据加载中...'

        // if (this.action === 'search') {
        //   method = 'getAllCustoms'
        // } else {
        //   method = 'getCustoms'
        // }
        this.getRollList(data).then((response) => {
          this.endLoading()
          if (response.data.errcode === 0) {
            this.total = response.data.results.total
            setTimeout(() => {
              that.mergeClientList(response.data.results.data)
              this.release()

              that.page_index++
              if (that.clientList.length > 0) {
                that.noDataText = ''
              } else {
                this.noDataText = this.originNoDataText
              }
            }, 300)

            if (that.clientList.length) {
              that.noDataText = ''
            }
          } else {
            this.noDataText = this.originNoDataText
            console.debug('系统服务异常！请联系管理员!', response.data.errmsg)
          }
          this.init = true
        }).catch(function (error) {
          this.noDataText = this.originNoDataText
          this.endLoading()
          this.init = true
          console.debug('系统服务异常！请联系管理员!', error)
        })
      },
      endLoading () {
        setTimeout(() => {
          if (this.$refs.my_scroller) {
            this.$refs.my_scroller.finishInfinite(true)
            this.$refs.my_scroller.finishPullToRefresh()
          }
        }, 300)
      },
      isSameObj (obj1, obj2) {
        return JSON.stringify(obj1) === JSON.stringify(obj2)
      },

      emptyCustoms () {
        this.clientList = []
        this.clientIDs = []
        this.page_index = 1
      },

      // 筛选器
      changeFilterValue (filterOptions) {
        var submitData = Object.assign({}, this.filterData)
        filterOptions.forEach((object, index) => {
          if (object.options) {
            object.options.forEach((secObject, secIndex) => {
              if (secObject.value === object.checked) {
                if (secObject.options) {
                  secObject.options.forEach((rdObj, rdIndex) => {
                    if (secObject.checked === rdObj.value) {
                      submitData[secObject.name] = rdObj.value
                    }
                  })
                } else {
                  submitData[object.name] = object.checked
                }
              }
            })
          }
        })
        let originalFilterData = this.filterData
        if (!this.isSameObj(originalFilterData, submitData)) {
          this.filterData = submitData
          this.emptyCustoms()
          this.getCustoms()
        }
      },
      ...mapActions({
        'getRollList': 'getRollList',
        'findTags': 'findTags',
        'queryObjectsByTag': 'queryObjectsByTag',
        'tagSign': 'tagSign',
        'queryCustomsByIds': 'queryCustomsByIds',
        'updateSourceFilter': 'updateSourceFilter',
        'updateChannelFilter': 'updateChannelFilter'
      })
    },

    computed: {
      ...mapState({
        isShowCover: state => state.app.isShowCover,
        loginUser: state => state.app.user,
        windowSize: state => state.app.windowSize,
        isUpdateSourceFilter: state => state.app.updateSourceFilter,
        isUpdateChannelFilter: state => state.app.updateChannelFilter,
        isAppMode: state => state.config.isAppMode,
        hasTeam: state => Object.keys(state.app.user.my_team_list).length > 0
      })

    },
    watch: {
      filterOptions () {
        console.debug('gbfilterOptions')
      },
      windowSize () {
        this.initSearchBodyHeight();
      },
      isShowSearch (val) {
        // if (val === true) {
        //   setTimeout(() => {
        //     this.initSearchBodyHeight()
        //   })
        // }
      }
    },

    mounted () {
      let query = this.$route.query
      this.action = query.action

      // 查重
      // if (this.action === 'search') {
      //   this.isShowSearch = true
      // }

      // if (!this.isUpdateSourceFilter) {
      //   getCustomSource(store).then((customSources) => {
      //     let sourceOptions = getSourceOptions(customSources)
      //     this.filterOptions[1].options.push(sourceOptions)
      //   })
      //   this.updateSourceFilter()
      // }

      // if (!this.isUpdateChannelFilter) {
      //   getChannelOptions().then((channelOptions) => {
      //     this.filterOptions[1].options.push(channelOptions)
      //   })
      //   this.updateChannelFilter()
      // }

      // this.noDataText = this.originNoDataText
      // this.tagSign()

      // // this.$refs.my_scroller.resize()

      // if (parseInt(query.is_sf) === 1) {
      //   this.selectFollow = true
      // }

      // this.custom_type = query.custom_type
      // const customType = parseInt(this.custom_type)
      // this.tagObjectCode = customType === 0 ? 'social_customer' : 'normal_customer'

      // loadTeamSettings().then((options) => {
      //   if (options === false) {
      //     this.filterTeamIndex = 0
      //     return
      //   }
      //   this.filterOptions = options[0]
      // })

      // loadMemberSettings().then((options) => {
      //   if (options === false) {
      //     this.filterMemberIndex = 0
      //     return
      //   }
      //   this.filterOptions = options[0]
      // })
      // this.getCustoms()
      this.clientList = []
      this.init = true
      this.noDataText = ''
    }

  }
</script>
<style lang="less">

  @import "../less/base";

  .soci-clients-list {

    margin-top: 20px;
    background-color: #EFEFF4;
    padding-top: 10px;

    .client-desc-name {
      font-size: 16px;
    }

    .pdscroll {
      background-color: #EFEFEF;
    }

    .bg-white{
      background-color: white;
      padding: 5px 0;
      &:extend(.clearfix all);

      .vux-x-icon {
        display: inline-block;
        vertical-align: middle;
        fill: #5AB1FF;
        margin-left: 8px;
        margin-right: 4px;
      }

    }

  }

  .new-add{
    position: fixed;
    z-index: 80;
    bottom: 60px;
    right: 26px;
    width: 40px;
    height: 40px;
    cursor: pointer;
    border-radius: 50%;
    padding: 2px;
    background-color: #fff;
    border: none;
    outline: none;
    box-shadow: 0 0 10px rgba(0,0,0,.15);
    font-weight: 700;
    display: block;
    line-height: 38px;
    text-align: center;
    background-color: #35ADFF;
    color: white;

  }

  .grey.container.pdt{
    padding-top: 18px;
  }

  .social-clients {
    .rela-tip-main {
      text-align: center;
      padding: 10px 0 2px;
    }

    .rela-result-tip {
      border-radius: 6px;
      line-height: normal;
      color: grey;
      padding: 4px 10px;
      overflow: hidden;
      display: inline-block;
    }

    .remove-ico {
      position: relative;
      height: 12px;
      width: 15px;
      margin-left: 4px;

      svg {
        position: absolute;
        left: 0;
      }
    }

    .cancel-blocker {
      float: left;
    }
    .remove-ico {
      display: inline-block;
    }

    .multi-search-list {
      height: 100%;
      overflow-x: hidden;
      overflow-y: scroll;
      padding-left: 20px;
      padding-top: 30px;
    }

    .multi-search-group {

    }


    .client-list-body {
    }

    .top-list-counter {
      // position: relative;
      // margin: 10px auto 0;
      border-radius: 10px;
      // padding: 2px;
      // line-height: 12px;
      // color: white;
      color: white;
      font-size: 12px;
      text-align: center;
      background-color: #CCCCCC;
    }
    .multi-search-item {
      line-height: normal;
      &.lighter {
        color: #1DBC5A;

        .item-icon {
          svg {
            color: #1DBC5A;
          }
        }
      }

      &:not(:last-child) {
        .item-rt {
          border-bottom: 1px solid #D4D4D7;
        }
      }

      .item-icon {
        padding: 12px 0;

        svg {
          // margin-top: 4px;
          color: #D4D4D7;
        }
      }

      overflow: hidden;
      display: flex;

      .search-item-value {
        flex: 1;
      }

      .item-rt {
        margin-left: 20px;
        flex: 1;
        display: flex;
        height: 16px;
        padding: 12px 0;
      }
    }

    .search-item-link {

      position: relative;
      width: 20px;
      height: 16px;
      margin-right: 20px;

      &:after {
        content: " ";
        display: inline-block;
        height: 6px;
        width: 6px;
        border-width: 2px 2px 0 0;
        border-color: #C8C8CD;
        border-style: solid;
        -webkit-transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
        transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
        position: relative;
        top: -2px;
        position: absolute;
        top: 50%;
        margin-top: -4px;
        right: 2px;
      }
    }
  }

</style>
